# 版权所有 2025 地球仪 (ldhhp@163.com)
# 本文件基于灯哥的 Py-Apple Dog 项目进行修改。
# 原始项目地址：https://github.com/ToanTech/py-apple-quadruped-robot
# 本项目遵循 Apache 许可证 2.0 版。
# 你可以在以下地址获取许可证副本：http://www.apache.org/licenses/LICENSE-2.0


import time
#链接网络
selfadd=None

def do_connect_STA(essid, password):
  global selfadd
  import network
  
  wifi = network.WLAN(network.STA_IF) 
  if not wifi.isconnected(): 
    print("正在连接设定的 WIFI："+essid)
    wifi.active(True)
    wifi.connect(essid, password) 
    while not wifi.isconnected():
      pass
  selfadd=wifi.ifconfig()[0]
  print("成功连接 WIFI："+essid)
  print("IP:"+ selfadd)

  time.sleep(0.5)
  
def do_connect_AP():
  global selfadd
  import network 
  wifi = network.WLAN(network.AP_IF) 
  wifi.config(essid='胖胖狗')
  if not wifi.isconnected(): 
    print('热点 WIFI 已开启，WIFI名称：胖胖狗')
    print('等待手机接入...')
    wifi.active(True) 
    while not wifi.isconnected():
      pass
  selfadd=wifi.ifconfig()[0]
  print("手机热点成功接入:IP "+selfadd)
  
  time.sleep(0.5)

def InitWifi():
    import setcfg          
    print("Mode: STA=" + str(setcfg.DAT["wifi"]["STA"]))    
    if setcfg.DAT["wifi"]["STA"]==0:
        do_connect_AP()
    else:
        do_connect_STA(setcfg.DAT["wifi"]["ESSID"],setcfg.DAT["wifi"]["PASSWORD"])


import socket

class LogToUdp:
    def __init__(self, port=8765):
        try:
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            self.sock.setblocking(False)
            self.broadcast_address = ("255.255.255.255", port)
        except Exception as e:
            print("LogToUdp:" + str(e))

    def Log(self, message):
        try:
            self.sock.sendto(message, self.broadcast_address)
        except Exception as e:
            print("Error log: "+str(e))
